#-------------------------------------------------------------------------------
# Copyright (c) 2012 Huseyin BIYIK.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Public License v3.0
# which accompanies this distribution, and is available at
# http://www.gnu.org/licenses/gpl.html
# 
# Contributors:
#     Huseyin BIYIK - initial API and implementation
#-------------------------------------------------------------------------------
import Queue, socket
from defs import *

class receive():
	def __init__(self, laddr, lport):
		self.close_flag = False
		self.lport = lport
		self.laddr = laddr
		self.sock_rcv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.sock_rcv.setblocking(1)
		self.sock_rcv.settimeout(5)
		logger.info("Listening on : %s:%s", self.laddr, self.lport)
		try:
			self.sock_rcv.bind((self.laddr, self.lport))
			self.laddr, self.lport = self.sock_rcv.getsockname()
		except socket.error:
			logger.error("Socket can not bind to adress: %s:%s. Closing interface", self.laddr, self.lport)
		logger.info("Network interface has been initialized")

	def close(self):
		self.close_flag = True
		logger.info("Closing receiving socket")
		self.sock_rcv.close()
		return True
	
	def receive(self):
		chunk=""
		try:
			while 1:
				tmp,addr=self.sock_rcv.recvfrom(udp_packet_size)
				if chunk != "":
					print "collected"
				chunk+=tmp
				if chunk[-len(end_marker):]==end_marker:
					return chunk[:-len(end_marker)],addr
		except socket.timeout, e:
			if self.close_flag:
				return (None, None)
			else:
				return (None, None)
		except socket.error, e:
			logger.error("Socket errror on receiving : %s", e)
			return (None, None)


class send():
	def __init__(self):
		self.sock_snd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
	
	def send(self, data, raddr, rport):
		try:
			self.sock_snd.sendto(data, (raddr, rport))
			return True
		except socket.error, e:
			logger.error("Socket error on sending : %s" , e)
			return False

	def close(self):
		logger.info("Closing sending socket")
		self.sock_snd.close()
		return True
